package com.zr.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.json.JSONArray;
import org.json.JSONObject;

import com.zr.dao.RoleDao;
import com.zr.model.Role;
import com.zr.util.JDBCUtil;

/**
 * @Description
 * @author 郑少杰
 * @date 2017年9月13日 下午3:36:39
 * @version V1.3.1
 */

public class RoleDaoImpl implements RoleDao {
    /**
     * Description 通过用户id查询角色信息
     * 
     * @param userId 用户id
     * @return 角色信息对象
     * @see com.zr.dao.UserDao#getRoleByUserId(int)
     */

    @Override
    public Role getRoleByUserId(int userId) {
        // TODO Auto-generated method stub
        Role role = new Role();
        StringBuffer sql = new StringBuffer();
        sql.append("select * ");
        sql.append("from role ");
        sql.append("where userid = ?");
        Connection connection = JDBCUtil.getConnection();
        PreparedStatement preparedStatement = null;
        try {
            preparedStatement = connection.prepareStatement(sql.toString());
            preparedStatement.setInt(1, userId);
            ResultSet resultSet = preparedStatement.executeQuery();
            if (resultSet.next()) {
                role.setUserId(resultSet.getInt("roleid"));
                role.setRoleName(resultSet.getString("rolename"));
                role.setUserId(resultSet.getInt("userid"));
                role.setFids(resultSet.getString("fids"));
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            JDBCUtil.closeJDBC(preparedStatement, connection);
        }

        return role;
    }

    /**
     * Description
     * 
     * @param parentId
     * @param fids
     * @return
     * @see com.zr.dao.RoleDao#getFuncsByParentId(int, java.lang.String)
     */

    @Override
    public JSONArray getFuncsByParentId(int parentId, String fids) {
        JSONArray jsonArray = new JSONArray();
        StringBuffer sql = new StringBuffer();
        sql.append("select * from function where fid in (");
        sql.append(fids);
        sql.append(") ");
        sql.append("and fpid = ?");
        Connection connection = JDBCUtil.getConnection();
        PreparedStatement preparedStatement = null;
        try {
            preparedStatement = connection.prepareStatement(sql.toString());
            preparedStatement.setInt(1, parentId);
            ResultSet resultSet = preparedStatement.executeQuery();
            while (resultSet.next()) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("id", resultSet.getInt("fid"));
                jsonObject.put("text", resultSet.getString("fname"));
                jsonObject.put("state", resultSet.getString("fstate"));
                JSONObject attr = new JSONObject();
                attr.put("furl", resultSet.getString("furl"));
                jsonObject.put("attributes", attr);

                jsonArray.put(jsonObject);
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            JDBCUtil.closeJDBC(preparedStatement, connection);
        }

        return jsonArray;
    }

    /**
     * Description
     * 
     * @param parentId
     * @param fids
     * @return
     * @see com.zr.dao.RoleDao#getCurrentUserFuncsByParentId(int, java.lang.String)
     */

    @Override
    public JSONArray getCurrentUserFuncsByParentId(int parentId, String fids) {
        JSONArray jsonArray = getFuncsByParentId(parentId, fids);

        for (int i = 0; i < jsonArray.length(); i++) {
            String state = jsonArray.getJSONObject(i).getString("state");
            if ("open".equals(state)) {
                continue;
            } else {
                int currentId = jsonArray.getJSONObject(i).getInt("id");
                JSONArray children = this.getCurrentUserFuncsByParentId(currentId, fids);
                jsonArray.getJSONObject(i).put("children", children);
            }
        }
        return jsonArray;
    }

    /**
     * Description
     * 
     * @return
     * @see com.zr.dao.RoleDao#selectRoles()
     */

    @Override
    public List<Role> selectRoles() {
        List<Role> list = new ArrayList<>();
        StringBuffer sql = new StringBuffer();
        sql.append("select * from role");
        Connection connection = JDBCUtil.getConnection();
        PreparedStatement preparedStatement = null;
        try {
            preparedStatement = connection.prepareStatement(sql.toString());
            ResultSet resultSet = preparedStatement.executeQuery();
            while (resultSet.next()) {
                Role role = new Role(resultSet.getInt("roleId"), resultSet.getString("rolename"),
                        resultSet.getInt("userid"), resultSet.getString("fids"));
                list.add(role);
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            JDBCUtil.closeJDBC(preparedStatement, connection);
        }

        return list;
    }

    /**
     * Description
     * 
     * @param page
     * @param pageSize
     * @return
     * @see com.zr.dao.RoleDao#getAllRoles(java.lang.String, java.lang.String)
     */

    @Override
    public List<Role> getAllRoles(int page, int pageSize) {
        List<Role> list = new ArrayList<>();
        StringBuffer sql = new StringBuffer();
        sql.append("select * ");
        sql.append("from role ");
        sql.append("limit ?,?");
        Connection connection = JDBCUtil.getConnection();
        PreparedStatement preparedStatement = null;
        try {
            preparedStatement = connection.prepareStatement(sql.toString());
            preparedStatement.setInt(1, (page - 1) * pageSize);
            preparedStatement.setInt(2, pageSize);
            ResultSet resultSet = preparedStatement.executeQuery();
            while (resultSet.next()) {

                Role role = new Role(resultSet.getInt("roleid"), resultSet.getString("rolename"),
                        resultSet.getInt("userid"), resultSet.getString("fids"));
                list.add(role);
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            JDBCUtil.closeJDBC(preparedStatement, connection);
        }
        return list;

    }

    /**
     * Description
     * 
     * @param childrenId
     * @return
     * @see com.zr.dao.RoleDao#getParent(int)
     */

    @Override
    public Set<Integer> getParent(Integer childrenIds) {
        Set<Integer> set = new HashSet<>();
        StringBuffer sql = new StringBuffer();
        sql.append("select fpid ");
        sql.append("from function ");
        sql.append("where fid =?");


        Connection connection = JDBCUtil.getConnection();
        PreparedStatement preparedStatement = null;
        try {
            preparedStatement = connection.prepareStatement(sql.toString());
            preparedStatement.setInt(1, childrenIds);
            ResultSet resultSet = preparedStatement.executeQuery();
            while (resultSet.next()) {
                int fpid = resultSet.getInt("fpid");

                set.add(fpid);
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            JDBCUtil.closeJDBC(preparedStatement, connection);
        }
        return set;
    }

    /**
     * Description
     * 
     * @param childrenIds
     * @return
     * @see com.zr.dao.RoleDao#getParents(java.lang.String)
     */

    @Override
    public Set<Integer> getParents(Integer childrenIds) {
        Set<Integer> set = getParent(childrenIds);
        for (Integer integer : set) {
            if (integer == -1) {
                continue;
            } else {
                Set<Integer> set2 = getParent(integer);
                set.addAll(set2);
            }
        }

        return set;
    }

    /**
     * Description
     * 
     * @param name
     * @param fids
     * @return
     * @see com.zr.dao.RoleDao#insertRole(java.lang.String, java.lang.String)
     */

    @Override
    public boolean insertRole(String name, String fids) {
        StringBuffer sql = new StringBuffer();
        sql.append("insert into role (rolename,fids) ");
        sql.append("values(?,?)");
        Connection connection = JDBCUtil.getConnection();
        PreparedStatement preparedStatement = null;
        try {
            preparedStatement = connection.prepareStatement(sql.toString());
            preparedStatement.setString(1, name);
            preparedStatement.setString(2, fids);
            int i = preparedStatement.executeUpdate();
            if (i > 0) {
                return true;
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            JDBCUtil.closeJDBC(preparedStatement, connection);
        }
        return false;
    }

    /**
     * Description
     * 
     * @param roleId
     * @return
     * @see com.zr.dao.RoleDao#selectFids(int)
     */

    @Override
    public Role selectFids(int roleId) {

        Role role = new Role();
        StringBuffer sql = new StringBuffer();
        sql.append("select * ");
        sql.append("from role ");
        sql.append("where roleId = ?");
        Connection connection = JDBCUtil.getConnection();
        PreparedStatement preparedStatement = null;
        try {
            preparedStatement = connection.prepareStatement(sql.toString());
            preparedStatement.setInt(1, roleId);
            ResultSet resultSet = preparedStatement.executeQuery();
            if (resultSet.next()) {
                role.setUserId(resultSet.getInt("roleid"));
                role.setRoleName(resultSet.getString("rolename"));
                role.setUserId(resultSet.getInt("userid"));
                role.setFids(resultSet.getString("fids"));
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            JDBCUtil.closeJDBC(preparedStatement, connection);
        }

        return role;
    }



}
